package practise_stack;

import java.util.Stack;

public class IsValid {

    public static int indexOf(Character c, Character[] type) {
        for (int i = 0; i < type.length; i++) {
            if(type[i] == c) {
                return i;
            }
        }
        return -1;
    }
    public boolean isValid(String s) {
        Character[] leftType = {'[', '{', '('};
        Character[] rightType = {']', '}', ')'};
        Stack<Character> stack = new Stack<>();
        int len = s.length();
        //遍历每个元素
        for (int i = 0; i < len; i++) {
            Character c = s.charAt(i);
            int index;

            if(indexOf(c, leftType) != -1) {//左括号
                stack.add(c);
            } else if((index = indexOf(c, rightType)) != -1) {//右括号
                //此时 index 表示右括号的下标 先要判断是否为空
                //再判断是否配对（观察左括号的下标与有括号的下标是否相等）
                if(stack.isEmpty() || indexOf(stack.pop(), leftType) != index) {
                    return false;
                }
            }
        }
        //如果不为空，那么左括号就多了 如果为空，就正确
        return stack.isEmpty();
    }
}
